package com.luocc.ccdemo.db

import android.app.Application
import android.os.Bundle
import androidx.lifecycle.LiveData
import com.luocc.ccdemo.entity.Result
import com.luocc.ccdemo.entity.Video
import com.luocc.ccdemo.utils.Api
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class VideoRepository(application: Application) {

    private val mVideoDao: VideoDao
    private val mFavoritesVideo: LiveData<List<Video>>

    init {
        val db = AppDatabase.getDatabase(application)
        mVideoDao = db.videoDao()
        mFavoritesVideo = mVideoDao.findFavorites()
    }

    fun getFavorites(): LiveData<List<Video>> {
        return mFavoritesVideo
    }

    fun insert(video: Video) {
        mVideoDao.insert(video)
    }

    fun update(video: Video) {
        mVideoDao.update(video)
    }

    fun clearFavorites() {
        mVideoDao.clearFavorites()
    }

    suspend fun delete(id: Int) {
        withContext(Dispatchers.IO) {
            mVideoDao.delete(id)
        }
    }

    suspend fun getVideo(size: Int): Result<Bundle> {
        return withContext(Dispatchers.IO) {
            Api.getHaoKanVideo(0, size)
        }
    }
}